$(document).ready(function() {
    $('#error').parent().parent().hide();
    $('#tpeDateBase').hide();
    $('#tpeCommentBase').hide();
    showMoreInfo($("#div_fpfv"), "imgInfoFpfv");
});

function validate(){
    setEmptyDates();

    $("#formCountry")
        .validate(
        {
            rules : {
                'protocoloAEditar.compromisopais.id' : "required"
            }
        });

    $(".numberClass").rules("add", {
        number :true
    });

    if($("#formCountry").valid() == false)
        return false;

    var idCell = "error";
    var labelCell = document.getElementById(idCell);

    var filled = false;
    $("#formCountry").find("input").each(function() {
        if ( this.value != "" && this.type != "hidden" && this.id != "save" && this.id != "new"){
            filled = true;
        }
    });
    if(filled == false){
        showError("At least one field is required");
        return false;
    }
    else{
        removeError();
    }

    var cantObj = document.getElementById("cantObjetivos");
    var ultimoId = document.getElementById("ultimoIdObjetivos");
    for(var x = 0; x<=ultimoId.value; x++){
        var hubActual = document.getElementById("hubField" + x);
        if (hubActual != null){
            var descrActual = document.getElementById("descrField" + x);
            if(hubActual.value == "" && descrActual.value == "" && cantObj.value != "1"){
                showError("Please complete or delete the empty objectives");
                return false;
            }
            if ( (hubActual.value != "" && descrActual.value == "") || (hubActual.value == "" && descrActual.value != "")){
                showError("Please complete year and description for all objectives");
                return false;
            }
        }
    }

    var cantTpe = document.getElementById("cantTpe");
    for(var y = 1; y<=cantTpe.value; y++){
        var tpeActual = document.getElementById("tpeCell" + y);
        var tpeDateActual = document.getElementById("tpeCellDate" + y);
    /*    if(tpeActual.value == "" && tpeDateActual.value == "" && cantTpe.value != "1"){
            showError("Please complete or delete the empty TPEs");
            return false;
        }*/
        if ( (tpeActual.value == "" && tpeDateActual.value != "") || (tpeActual.value != "" && tpeDateActual.value == "") ){
            showError("Please complete TPE and TPE Date for all TPEs");
            return false;
        }
        if( tpeActual.value != "" && !jQuery.isNumeric(tpeActual.value) ){
            showError("Target Patient Enrolled field must be numeric");
            return false;
        }
    }

    removeError();

    return true;
}



function validateGlobal(){
    $(".datepicker").each(function(i,v){
        if($(v).val() == ''){
            var idAlt = "#alt" + v.id;
            $(idAlt).val('');
        }
    });
}


function showError(msg){
    var label = document.getElementById("error");
    label.innerHTML = msg;
    $('#error').parent().parent().show();
}

function removeError(){
    $('#error').parent().parent().hide();
}

function isGlobalCommitment(select){
    if ($("#pais option:selected").text() == "Global")
        $("#formCountry").submit();
}

function deleteObjective(tableId, fila){
    var table = document.getElementById(tableId);
    var cant = document.getElementById("cantObjetivos");

    var rows = table.getElementsByTagName('tr');
    var size = rows.length;
    for(var j = 0; j < rows.length; j++ ){
        if(rows[j].id == fila[0].id && rows[j].cells[0].id == fila[0].cells[0].id){
            break;
        }
    }

    if(cant.value == 1){
        var borrados = 0;
        var x = j - 1;
        while(borrados < 2){
            if(rows[x].cells[1] != null){
                rows[x].cells[1].children[0].value="";
                borrados++;
            }
            x--;
        }
        return;
    }

    var borrados = 0;
    var x = j;
    while(borrados < 3){
        rows[x].parentNode.removeChild(rows[x]);
        if(rows[x].cells[1] != null){
                borrados++;
        }
        x--;
    }

    var val = parseInt(cant.value,10) - parseInt(1,10);
    cant.value = val;
}


function addObjective(tableID){
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

    var cant = document.getElementById("cantObjetivos");
    var val = parseInt(cant.value,10) + parseInt(1,10);
    cant.value = val;

    var ultimoId = document.getElementById("ultimoIdObjetivos");

    for(var k = ultimoId.value; k>0; k--){
        if (document.getElementById("delObjCell" + k) != null)
            break;
    }

    var newId = parseInt(ultimoId.value,10) + parseInt(1,10);
    ultimoId.value = newId;

    var idAfter = '#delObjCell' + k;

    var row5 = $('#delObjCell' + k).parent().clone()[0];
    row5.cells[0].id="delObjCell"+newId;
    row5.cssClass="trNuevoDocumento";
    $(idAfter).parent().after(row5);

    var row4 = $('#descrField' + k).parent().parent().clone()[0];
    row4.cells[1].children[0].name="protocoloAEditar.objetivos[" + newId + "].objetivo";
    row4.cells[1].children[0].value="";
    row4.cells[1].children[0].id="descrField" + newId;
    $(idAfter).parent().after(row4);

    var row3 = $('#hubField' + k).parent().parent().clone()[0];
    row3.cells[1].children[0].name="protocoloAEditar.objetivos[" + newId + "].fecha";
    row3.cells[1].children[0].id="hubField" + newId;
    row3.cells[1].children[0].value="";
    $(idAfter).parent().after(row3);

}

function deleteTpe(tableId){
    var table = document.getElementById(tableId);
    var cant = document.getElementById("cantTpe");

    if(cant.value == 1){
        document.getElementById("tpeCell1").value = "";
        document.getElementById("tpeCellRand1").value = "";
        return;
    }

    $("#tpeCell" + cant.value).parent().parent().remove();
    $("#tpeCellRand" + cant.value).parent().parent().remove();
    $("#tpeCellDate" + cant.value).parent().parent().remove();
    $("#tpeCellCategory" + cant.value).parent().parent().remove();
    $("#tpeCellComment" + cant.value).parent().parent().remove();

 /*   var cell1 = document.getElementById("tpe" + cant.value);
    cell1.parentNode.removeChild(cell1);
    var cell2 = document.getElementById("tpeDate" + cant.value);
    cell2.parentNode.removeChild(cell2);
    var cell3 = document.getElementById("tpeComment" + cant.value);
    cell3.parentNode.removeChild(cell3);*/

     var val = parseInt(cant.value,10) - parseInt(1,10);
     cant.value = val;
}


function addTpe(tableID){
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

    var cant = document.getElementById("cantTpe");
    if(cant.value == 5)
        return;

    if(cant.value == 1)
        var idAfter = '#tpeCellRand' + cant.value;
    else
        var idAfter = '#tpeCellComment' + cant.value;

    if($('#tpeCellRand'+ cant.value).val() == "" && $('#tpeCell'+ cant.value).val() == ""){
        alert("Please fill the " + cant.value + "° TPE before adding a new one"); //TODO cambiar notificacion
        return;
    }

    var cantAnterior = cant.value;

    var val = parseInt(cant.value,10) + parseInt(1,10);
    cant.value = val;

    var row5 = $('#tpeCommentBase').clone()[0];
    row5.id="tpeComment" +cant.value;
    row5.cells[1].children[0].name="protocoloAEditar.enrolledPatients[" + cantAnterior+ "].comment";
    row5.cells[1].children[0].value="";
    row5.cells[1].children[0].id="tpeCellComment" + cant.value;
    $(row5).show();
    $(idAfter).parent().parent().after(row5);


    var row4 = $('#tpeCategoryBase').clone()[0];
    row4.id="tpeCategory" +cant.value;
    row4.cells[1].children[0].name="protocoloAEditar.enrolledPatients[" + cantAnterior+ "].category";
    row4.cells[1].children[0].value="-1";
    row4.cells[1].children[0].id="tpeCellCategory" + cant.value;
    $(row4).show();
    $(idAfter).parent().parent().after(row4);

    var row3 = $('#tpeDateBase').clone()[0];
    row3.id="tpeDate" + cant.value;
    row3.cells[1].children[0].name="";
    row3.cells[1].children[1].name="protocoloAEditar.enrolledPatients[" + cantAnterior + "].targetEnrolledDate";
    row3.cells[1].children[0].value="";
    row3.cells[1].children[0].id="tpeCellDate" + cant.value;
    row3.cells[1].children[1].id="alttpeCellDate" + cant.value;
    $(row3).show();
    $(idAfter).parent().parent().after(row3);
    initializeDate("#tpeCellDate" + cant.value,"#alttpeCellDate" + cant.value );

    /*        <s:hidden name="budget.dateRevised" id="altdRevised" value="%{budget.dateRevised}"/>
     <s:textfield label="Date Revised" id="dRevised" cssClass="datepicker"/>*/


    var row2 = $('#tpeCellRand1').parent().parent().clone()[0];
    row2.cells[1].children[0].name="protocoloAEditar.enrolledPatients[" + cantAnterior + "].targetEnrolledRandomized";
    row2.cells[1].children[0].value="";
    row2.cells[1].children[0].id="tpeCellRand" + cant.value;
    row2.cells[0].children[0].innerHTML=cant.value + "° Target Pts Enrolled Randomized";
    $(row2).removeClass("trEspacioAbajo");
    $(idAfter).parent().parent().after(row2);

    var row1 = $('#tpeCell1').parent().parent().clone()[0];
    row1.cells[1].children[0].name="protocoloAEditar.enrolledPatients[" + cantAnterior + "].targetEnrolledAmount";
    row1.cells[1].children[0].value="";
    row1.cells[1].children[0].id="tpeCell" + cant.value;
    row1.cells[0].children[0].innerHTML=cant.value + "° Target Patients Enrolled";
    $(idAfter).parent().parent().after(row1);
}

function updateDatepickers(){
    $('.datepicker').each(function(i,v){
        var idAlt = "#alt" + v.id;
        $(v).removeClass('hasDatepicker').datepicker({ dateFormat: 'dd/M/y', altField : idAlt, altFormat: 'dd/mm/y'});
    });}